package com.example.client_anna.network.okhttp3;

import com.example.client_anna.network.okhttp3.HttpUtil;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

/**
 * @author cy
 * @email 272884043@qq.com
 * @date 2021/10/19
 */
//okhttp3网络通讯工具类
public class HttpUtilImpl {
    public static void sendHttpRequest(final String address,final
    HttpUtil listener) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    if (listener != null) {
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if (listener != null) {
                        listener.onError(e);
                    }
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }

            }
        }).start();

    }
    public static void sendOKHttpRequest(String address,RequestBody requestBody,okhttp3.Callback callback){
        //创建okhttp实例
        OkHttpClient client=new OkHttpClient();
        //创建request对象,发起请求
        Request request=new Request.Builder()
                .url(address)
                .post(requestBody)
                .build();
        //请求超时
        OkHttpClient client1 = client.newBuilder()
                .readTimeout(3000,TimeUnit.MILLISECONDS)
                .build();
        //创建call对象,并调用enqueue方法来发送请求并获取服务器返回的数据
        client1.newCall(request).enqueue(callback);
    }
}
